package ua.yandex.skipass;

/**
 *
 * @author Кирилл
 */
public class TurnstileSystem {
    private static final int DEFAULT_NUMBER_OF_TURNSTILES = 1;
    private static final int DEFAULT_TURNSTILE = 0;
    
    private static TurnstileSystem system;
    private static SkiPassSystem headControl;
    
    private static class Turnstile {
        private int numberOfPasses;
        private int numberOfSuccesfullPasses;
        
        public  boolean isAllowed(SkiPassCard card) {
            boolean canPass = headControl.checkSkiPass(card);
            
            numberOfPasses++;
            if (canPass) {
                numberOfSuccesfullPasses++;
            }
            return canPass;
        }
    }
    
    private Turnstile[] listOfAvailableTurnstiles;
    
    private TurnstileSystem() {
        setNumberOfTurnstiles(DEFAULT_NUMBER_OF_TURNSTILES);
        // Did you mean to not hardcode constant ?
        // Ok, it is my default value of amount
        // of turnstiles unless you speciafy it.
    }
    
    public static TurnstileSystem getInstance() {
        if (system == null) {
            system = new TurnstileSystem();
        }
        return system;
    }
    
    public void setNumberOfTurnstiles(int turnstileNumber) {
        listOfAvailableTurnstiles = new Turnstile[turnstileNumber];
        for (int i = 0; i < turnstileNumber; i++) {
            listOfAvailableTurnstiles[i] = new Turnstile();
        }
    }
    
    public static void linkToControlSystem(SkiPassSystem sys) {
        headControl = sys;
    }
    
    public int getNumberOfTurnstiles() {
        return listOfAvailableTurnstiles.length;
    }
    
    public boolean checkSkiPass(SkiPassCard card) {
        return checkSkiPass(card, DEFAULT_TURNSTILE);
    }
    
    public boolean checkSkiPass(SkiPassCard card, int turnstileIndex) {
        if (turnstileIndex >= this.getNumberOfTurnstiles() ||
            turnstileIndex < 0) {
            throw new OutOfBoundException("Required turnstile does not exist");
        }
        System.out.println("turns");
        Turnstile turn = listOfAvailableTurnstiles[turnstileIndex];
        return turn.isAllowed(card);
    }
    
}
